package cn.intotw.pp.encode;

import cn.intotw.pp.constants.Constant;
import cn.intotw.pp.entity.PPProtocolFrame;
import cn.intotw.pp.entity.response.ServerBaseRes;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.List;

/**
 * @author Chenxiang
 * @Description:
 * @create 2018/9/11 14:49
 */
public class MessageEncoder extends MessageToMessageEncoder<ServerBaseRes> {
    protected void encode(ChannelHandlerContext channelHandlerContext, ServerBaseRes serverBaseRes, List<Object> list) throws Exception {
        StringBuffer stringBuffer=new StringBuffer();
        Field[] headFields=serverBaseRes.getClass().getSuperclass().getDeclaredFields();
        for (int i = 0; i < headFields.length; i++) {
            PropertyDescriptor fieldprop = new PropertyDescriptor(headFields[i].getName(), serverBaseRes.getClass());
            Object obj=fieldprop.getReadMethod().invoke(serverBaseRes, new Object[0]);
            String value = obj==null?"":(String)obj ;
            stringBuffer.append(value);
            if(i!=headFields.length-1)
            {
                stringBuffer.append(Constant.RES_HEAD_SPLIT);
            }
        }
        stringBuffer.append(Constant.RES_SPLIT);
        Field[] bodyFields=serverBaseRes.getClass().getDeclaredFields();
        for (int i = 0; i < bodyFields.length; i++) {
            PropertyDescriptor fieldprop = new PropertyDescriptor(bodyFields[i].getName(), serverBaseRes.getClass());
            Object obj=fieldprop.getReadMethod().invoke(serverBaseRes, new Object[0]);
            String value = obj==null?"":(String)obj ;
            stringBuffer.append(value);
            if(i!=bodyFields.length-1)
            {
                stringBuffer.append(Constant.RES_BODY_SPLIT);
            }
        }
        String res=stringBuffer.toString();
        byte[] resBytes=res.getBytes();
        PPProtocolFrame ppProtocolFrame=new PPProtocolFrame();
        ppProtocolFrame.setContentLength(resBytes.length);
        ppProtocolFrame.setContent(resBytes);
        list.add(ppProtocolFrame);
    }
}